import { encodeBase64 } from "./base64";

function getHeaders() {
  let headers: HeadersInit = {
    "content-type": "application/json",
  };

  const auth_cfg = process.env.NEXT_PUBLIC_AUTH;
  if (auth_cfg) {
    headers = { ...headers, Authorization: `Basic ${encodeBase64(auth_cfg)}` };
  }
  return headers;
}

const _fetch = async (url: string, method?: string, body?: BodyInit | null) =>
  (
    await fetch(`${process.env.NEXT_PUBLIC_API_URL}${url}`, {
      method,
      body,
      headers: getHeaders(),
      cache: "no-store",
    })
  ).json();

export const GET = async (url: string) => _fetch(url, "GET");

export const DELETE = async (url: string) => _fetch(url, "DELETE");

export const POST = async (url: string, body: any) =>
  _fetch(url, "POST", JSON.stringify(body));

export const PUT = async (url: string, body: any) =>
  _fetch(url, "PUT", JSON.stringify(body));
